'use strict'

const WebSocket = require('ws')
const SUN = require('../base/sun')
const rootSerConfig = SUN.serConfig.rootSerConfig
const route = require('../module/route')
const util = require('util')
const playerSessionMgr = require('../core/playerSessionMgr')

class GateClient {
    constructor() {
        this.gateClient = null
        this.callbacks = {}
        this.reqId = 1
    }

    createClient() {
        let self = this
        let gateClient = new WebSocket(`ws://${rootSerConfig.ip}:${rootSerConfig.port}`)
        this.gateClient = gateClient
        gateClient.on('open', function open() {
            console.info('连接网关服务器成功')
            self.callRemoteFunc('bindNodeName', {
                nodeName: SUN.serName,
                nodeType: SUN.serType
            })

            self.callRemoteFunc('getRequestRoute', {
                routeName: route.getAllRoute(),
                errMap: route.errMap,
                nodeType: SUN.serType
            })
        })

        gateClient.on('message', function message(data, flags) {
            try {
                data = JSON.parse(data)
                if (!util.isObject(data.msg)) {
                    data.msg = {}
                }
            } catch (e) {
                return
            }
            let uId = data.uId
            let player = playerSessionMgr.getPlayerByUid(uId)
            let method
            if (player) {
                method = route.get(data.route)
                if (method) {
                    method(player, data.msg, function(err, result) {
                        self.sendMsg(err, result, data.reqId)
                    })
                } else {
                    console.info(`角色已经登陆,${data.route}方法不存在`)
                }
            } else {
                method = route.getNotLogin(data.route)
                if (method) {
                    method(uId, data.msg, function(err, result) {
                        self.sendMsg(err, result, data.reqId)
                    })
                } else {
                    console.info(`角色未登陆,${data.route}方法不存在`)
                }
            }
        })

        gateClient.on('close', function close() {
            //保存所有用户后清空 session
            console.info('网关服务器断开连接')
            self.gateClient = {}
            self.gateClient.send = function() {}
        })
    }

    sendMsg(err, msg, reqId) {
        var sendData = {
            err: err,
            msg: msg
        }
        if (reqId) {
            sendData['reqId'] = reqId
        }
        sendData = JSON.stringify(sendData)
        this.gateClient.send(sendData)
    }

    //调用根节点的远程方法
    callRemoteFunc(route, msg) {
        var sendData = {
            msg: msg,
            route: route
        }

        sendData = JSON.stringify(sendData)
        this.gateClient.send(sendData)
    }
}


module.exports = GateClient
